import { PlusOutlined } from '@ant-design/icons'
import axios from 'axios'
import {
  Col,
  Row,
  Flex,
  Typography,
  Button,
  Input,
  Cascader,
  Form,
  Table,
  Alert,
  Switch,
  Image,
  message,
  Select,
  Tag
} from 'antd'
import React from 'react'
import { useEffect } from 'react'
import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import {adminActivatyStatus, adminCouponList, couponDel, couponStatus,exportCouponExcel} from '../service/activaty'
import {categoryDel, categoryEdit} from "../service/content";
import {serverURL} from "../utils/tools";
function ShopQrcode() {
  const navigate = useNavigate()
  const [qrcodeList, setQrcodeList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageNo, setPageNo] = useState(1)
  const [condition, setCondition] = useState({})
  // 保存表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 二维码可见
  const [visible, setVisible] = useState(false)
  // 弹出二维码路径
  const [qrcodeUrl, setQrcodeUrl] = useState('')
  const [n, setN] = useState(1)
  // 导出加载状态
  const [exportLoading, setExportLoading] = useState(false)
  useEffect(() => {
    ;(async () => {
      const res = await adminCouponList({
        ...condition,
        pageNo,
        pageSize: 10
      })
      if (res.data) {
        setQrcodeList(res.data.objects)
        setTotal(res.data.total)
      }
      console.log(res)
    })()
  }, [n])

  // Excel导出功能
  const handleExportExcel = async () => {
    try {
      // 显示加载状态
      // setExportLoading(true)
      // message.loading('正在导出数据，请稍候...', 0)
      // 构建导出参数，包含当前查询条件
      const exportParams = {
        ...condition,
        // 可以添加额外的导出参数
        exportType: 'excel'
      }
      const response = await axios({
        baseURL: serverURL,
        timeout: 5000,
        method: 'post',
        url: serverURL +'/admin/marketing/coupon/info/exportCouponExcel',
        data: exportParams,
        responseType: 'blob',  // 必须指定为blob类型
        headers: {
          'Content-Type': 'application/json'
        }
      });

      // 处理返回的文件流
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '优惠券列表.xlsx'
      document.body.appendChild(a)
      a.click()

      // 清理资源
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      message.success('优惠券数据导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      message.error('导出失败，请重试')
    } finally {
      // 隐藏加载状态
      setExportLoading(false)
    }
  }

  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'} >
            <Typography.Title level={3}>优惠券管理</Typography.Title>
            <div>
              <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => navigate('/admin/market/addCoupon')}
              >
                新建优惠券
              </Button>

              {/* 导出Excel按钮 */}
              <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleExportExcel}
                  loading={exportLoading}
                  style={{ marginLeft: 4 }}
              >
                导出Excel
              </Button>

            </div>

          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form
            layout="inline"
            onFinish={async (v) => {
              console.log(v)
              // setCondition({
              //   storeName: v.storeName,
              //   storeAddress: v.storeAddress ? v.storeAddress.join() : ''
              // })
              console.log(condition)
              // const res = await adminCouponList({
              //   ...condition,
              //   pageNo,
              //   pageSize: 10
              // })
              // console.log(res)
              setCondition(v)
              setN(n + 1)
              // setQrcodeList(res.data.objects)
              // setTotal(res.data.total)
            }}
          >
            <Form.Item label="优惠券名称" name="couponName">
              <Input />
            </Form.Item>
            <Form.Item
              label="优惠券类型"
              name="couponType"
              initialValue={'0'}
            >
              <Select
                options={[
                  { value: '0', label: '全部' },
                  { value: '1', label: '满减' },
                  { value: '2', label: '折扣' },
                  { value: '3', label: '随机' }
                ]}
                style={{ width: 200 }}
              />
            </Form.Item>
            <Form.Item label="优惠券状态" name="enableStatus" initialValue={'0'}>
              <Select
                options={[
                  { value: '0', label: '全部' },
                  { value: '1', label: '未开始' },
                  { value: '2', label: '进行中' },
                  { value: '3', label: '已结束' }
                ]}
                style={{ width: 200 }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="default" htmlType="reset">
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      {/* 表格 */}
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            优惠券列表
          </Typography.Paragraph>
          {hasSelected && (
            <Alert
              message={`已经选择 ${selectedRowKeys.length} 项`}
              type="info"
              showIcon
            />
          )}
        </Col>
        <Col span={24}>
          <Table
            pagination={{
              total,
              defaultCurrent: 1,
              onChange: async (page) => {
                const res = await adminCouponList({
                  ...condition,
                  pageNo: page,
                  pageSize: 10
                })
                setQrcodeList(res.data.objects)
                // setTotal(res.data.total)
              }
            }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (newSelectedRowKeys) => {
                console.log('selectedRowKeys changed: ', newSelectedRowKeys)
                setSelectedRowKeys(newSelectedRowKeys)
              }
            }}
            dataSource={qrcodeList}
            columns={[
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '优惠券名称',
                dataIndex: 'couponName',
                key: 'couponName'
              },
              {
                title: '适用范围',
                dataIndex: 'applicable',
                key: 'applicables'
              },
              {
                title: '优惠内容',
                dataIndex: 'describes',
                key: 'describes'
              },
              {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (_, record) => {
                  switch (record.status) {
                    case 0:
                      return <Tag color="blue">未开始</Tag>
                    case 1:
                      return <Tag color="green">进行中</Tag>
                    case 2:
                      return <Tag color="red">已结束</Tag>
                    default:
                      return <Tag color="blue">未开始</Tag>
                  }
                }
              },
              {
                title: '数量',
                dataIndex: 'usageNum',
                key: 'usageNum',
                render: (_, record) => {
                  return <>{record.usageNum}张</>
                }
              },
              {
                title: '有效期',
                dataIndex: 'startDate',
                key: 'startDate',
                render: (_, record) => {
                  return (
                    <>
                      {record.startDate.substring(0, 10)} -{' '}
                      {record.endDate.substring(0, 10)}
                    </>
                  )
                }
              },
              // {
              //   title: '启用状态',
              //   dataIndex: 'enableStatus',
              //   key: 'enableStatus',
              //   render: (_, record) => {
              //     return <Switch checked={record.enableStatus === 1}
              //                    onChange={async (value) => {
              //                      console.log(value)
              //                      if (value) {
              //                        const res = await couponStatus({
              //                          id: record.id,
              //                          enableStatus: 1
              //                        })
              //                        console.log(res)
              //                        message.success('开启成功')
              //                      } else {
              //                        const res = await couponStatus({
              //                          id: record.id,
              //                          enableStatus: 0
              //                        })
              //                        console.log(res)
              //                        message.success('关闭成功')
              //                      }
              //                    }}
              //     />
              //   }
              // },


              {
                title: '启用状态',
                dataIndex: 'enableStatus',
                key: 'enableStatus',
                render: (_, record) => (
                    <Switch
                        defaultChecked={record.enableStatus === 1}
                        onChange={async (value) => {
                          console.log(value)
                          if (value) {
                            const res = await couponStatus({
                              id: record.id,
                              enableStatus: 1
                            })
                            console.log(res)
                            message.success('开启成功')
                          } else {
                            const res = await couponStatus({
                              id: record.id,
                              enableStatus: 0
                            })
                            console.log(res)
                            message.success('关闭成功')
                          }
                        }}
                    />
                )
              },


              {
                title: '操作',
                dataIndex: 'op',
                key: 'op',
                align: 'center',
                render: (_, record) => {
                  return (
                    <span className="op">
                      <Link to={`/admin/market/editCoupon/${record.id}`}>
                        编辑
                      </Link>
                      <a onClick={async () => {
                        const res = await couponDel({ id: record.id })
                        console.log(res)
                        if (res.code === '0') {
                          message.success('删除优惠券成功！')
                          setN(n + 1)
                        }
                      }}>删除</a>
                    </span>
                  )
                }
              }
            ]}
          />
        </Col>
      </Row>
      <Image
        width={200}
        style={{
          display: 'none'
        }}
        src={qrcodeUrl}
        preview={{
          className: 'centerBox',
          width: 220,
          visible,
          src: { qrcodeUrl },
          onVisibleChange: (value) => {
            setVisible(value)
          }
        }}
      />
    </>
  )
}

export default ShopQrcode
